<script setup lang="ts">
import { computed, onActivated, onMounted, ref, watch } from 'vue';

import { useAccess } from '@vben/access';
import { getPopupContainer } from '@vben/utils';

import { message, Tooltip } from 'ant-design-vue';

import { employeeQuerySensitive } from '#/api/company/audience';

import { useClinkCall } from './useClink';

interface Props {
  employeeId?: number | string;
  phoneNumber?: number | string;
  autoLogin?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  employeeId: undefined,
  phoneNumber: '',
  autoLogin: false,
});

const emit = defineEmits<{
  (e: 'callEnd', uniqueId: string): void;
}>();

const {
  initialized,
  isLogin,
  loading,
  tip,
  isCalling,
  activePhone,
  agentInfo,
  login,
  call,
  hangup,
  setupClinkToolbar,
} = useClinkCall({
  onCallEnd: (uniqueId: string) => {
    emit('callEnd', uniqueId); // 呼叫结束事件传递给父组件
  },
  onIdle: () => {
    hangup();
  },
});

// const currPhoneNumber = ref(props.phoneNumber);
// watch(
//   () => props.phoneNumber,
//   (val) => {
//     if (val) {
//       currPhoneNumber.value = val;
//     }
//   },
// );

const fullPhone = ref<string>();
const isActive = computed(() => activePhone.value === fullPhone.value);

const setDisabled = ref(false);
const buttonDisabled = computed(() => {
  if (!initialized.value) {
    // 电话条插件未初始化成功
    return true;
  }
  if (!isLogin.value) {
    // 电话条初始化成功，未登录成功
    return true;
  }
  if (!isActive.value && isCalling.value) {
    // 其它号码按钮呼叫中，需禁用当前按钮
    return true;
  }

  if (setDisabled.value) {
    // 其它禁用
    return true;
  }

  // 无手机号时可呼时禁用
  return !props.phoneNumber;
});

const callTip = ref<string>('');
watch(
  () => tip.value,
  (val) => {
    if (val && isActive.value) {
      // 当前呼叫的手机号的tip结果
      // console.log('activePhone', activePhone.value);
      // console.log('callTip', `${props.phoneNumber}: ${val}`);
      callTip.value = val;

      if (val.includes('禁呼')) {
        setDisabled.value = true;
      }
    }
  },
);
const tipTitle = computed(() => {
  if (callTip.value) {
    return callTip.value;
  }
  if (loading.value) {
    return '初始化中';
  }
  if (!initialized.value) {
    return '呼叫插件安装失败';
  }
  if (!agentInfo.value) {
    return '暂无可用坐席';
  }
  if (!isLogin.value) {
    return '坐席未登录';
  }

  if (!props.phoneNumber) {
    return '当前无电话号码，无法呼叫';
  }

  // if (isActive.value) {
  //   return tip.value;
  // }

  return '';
});

const btnText = computed(() => {
  let text = '呼叫';
  if (isActive.value && isCalling.value) {
    text = '挂断';
  }
  return text;
});

const { hasAccessByCodes } = useAccess();

async function handleClick() {
  console.log('handleClick', isCalling.value);
  if (isActive.value && isCalling.value) {
    hangup();
  } else {
    if (hasAccessByCodes(['employee:manager:sensitive'])) {
      loading.value = true;
      const fullPhoneNumber = await employeeQuerySensitive({
        employeeId: props.employeeId,
        accessPage: 5,
        accessField: 1,
      });
      loading.value = false;
      if (fullPhoneNumber) {
        fullPhone.value = fullPhoneNumber;
        call(fullPhoneNumber);
      } else {
        message.error('手机号查询失败');
      }
    } else {
      message.warning('您没有权限操作');
    }
  }
}

onMounted(() => {
  if (props.autoLogin) {
    setupClinkToolbar(null);
  } else {
    loading.value = false;
  }
});

// 处理页面切换回来时
onActivated(() => {
  console.log('处理页面切换回来时');
  console.log('loading:', loading.value);
  console.log('initialized:', initialized.value);
  console.log('isLogin:', isLogin.value);
  if (props.autoLogin) {
    if (!loading.value && !isLogin.value) {
      login();
    }
  } else {
    loading.value = false;
  }
});

defineExpose({
  loading,
  isLogin,
  isCalling,
  activePhone,
  call,
  hangup,
});
</script>

<template>
  <Tooltip
    :get-popup-container="getPopupContainer"
    placement="leftTop"
    arrow-point-at-center
    :title="tipTitle"
  >
    <ghost-button
      class="flex items-center"
      :class="{ 'btn-success': !isCalling }"
      :loading="loading"
      :disabled="
        !initialized || (!loading && buttonDisabled) || (!isActive && isCalling)
      "
      :danger="isActive && isCalling"
      @click="handleClick"
    >
      <template #icon>
        <span class="icon-[ant-design--phone-outlined] mr-[2px]"></span>
      </template>
      {{ btnText }}
    </ghost-button>
  </Tooltip>
</template>

<style lang="scss">
#tinet-toolbar .tinet-header .tinet-status-host .tinet-status {
  display: none !important;
}
</style>
